package com.project.dao.Impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.project.dao.ProductDao;
import com.project.util.Fileupload;
import com.project.util.StringUtil;
import com.project.vo.Picture;
import com.project.vo.Product;

public class ProductDaoImpl implements ProductDao {

	private SessionFactory sessionFactory;
	private Product product;
	private Picture picture;
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	public Session getSession() {
		return session;
	}
	public void setSession(Session session) {
		this.session = session;
	}
	public Session session = null;
	@Override
	public String add(Product product) {
		// TODO Auto-generated method stub
		String result = StringUtil.FAILURE;
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			session.save(product);
			session.getTransaction().commit();
			result = StringUtil.SUCCESS;
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			session.getTransaction().rollback();
		} finally {
			session.close();
		}
		return result;
	}
	@Override
	public String add(Product product, List<String> localPath) {
		// TODO Auto-generated method stub
		String result = StringUtil.FAILURE;
		Set pictures = new HashSet<>();
		for (int i = 0; i < localPath.size(); i++) {
			Picture picture = new Picture();
			picture.setPath(localPath.get(i));
			pictures.add(picture);
		}
//		product.setPictures(pictures);
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			session.save(product);		//总是出错，class not declear ,没有声明类，picture的原因
			session.getTransaction().commit();
			result = StringUtil.SUCCESS;
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			session.getTransaction().rollback();
		} finally {
			session.close();
		}
		return result;
	}
	@Override
	public String add(Product product, Set pic) {
		// TODO Auto-generated method stub
		String result = StringUtil.FAILURE;
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			session.save(product); 
			Integer productId = product.getId(); 
			Iterator<Picture> pIterator = pic.iterator();
			while (pIterator.hasNext()) {
				Picture pict = pIterator.next(); 
				Picture picture = new Picture();
				picture.setPath(pict.getPath());
				picture.setProduct_id(productId);
				session.save(picture);				
			}
			session.getTransaction().commit();
			result = StringUtil.SUCCESS;
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			session.getTransaction().rollback();
		} finally {
			session.close();
		}
		return result;
	}
	
	@Override
	public String add(Product product, List<File> pictures, List<String> picturesFileName) {
		String result = StringUtil.FAILURE;
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			session.save(product); 
			Integer productId = product.getId(); 
			Iterator<File> pIterator = pictures.iterator();
			String dir = StringUtil.F_SAVE_DIRECTORY+"/"+ product.getUser_id() + "/" + product.getId() +"/";
			String loadRes = Fileupload.uploadFiles(dir, pictures, picturesFileName);
			if (!loadRes.equals(StringUtil.SUCCESS)) {
				return StringUtil.FAILURE;
			}
			String savePath = StringUtil.F_SAVE_PATH +"/"+ product.getUser_id() + "/" + product.getId() +"/";
			List<String> localPath = Fileupload.getLocalPaths(picturesFileName, savePath);
			//处理图片
			for (int i = 0; i < localPath.size(); i++) {
				Picture picture = new Picture();
				picture.setPath(localPath.get(i));
				picture.setProduct_id(productId);
				session.save(picture);	
			}
			session.getTransaction().commit();
			result = StringUtil.SUCCESS;
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			session.getTransaction().rollback();
		} finally {
			session.close();
		}
		return result;
	}
	public String addPictures(Set pic) {
		String result = StringUtil.FAILURE;
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			Iterator<Picture> pIterator = pic.iterator();
			while (pIterator.hasNext()) {
				session.save(pIterator.next());				
			}
			session.getTransaction().commit();
			result = StringUtil.SUCCESS;
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			session.getTransaction().rollback();
		} finally {
			session.close();
		}
		return result;
	}
	@Override
	public List<Product> queryAllByUserId(Integer user_id, int pageSize, int pageNum) {
		// TODO Auto-generated method stub
		String hql = "from Product product where product.user_id = ?";
		List<Product> products = new ArrayList<Product>();
		try {
			session = sessionFactory.openSession();
			Query query = session.createQuery(hql);
			query.setParameter(0, user_id);
			query.setFirstResult((pageNum-1)*pageSize);
			query.setMaxResults(pageSize);
			products = query.list();
			System.out.println(products.size());
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
		}catch (IllegalArgumentException e) {//没有数据
			// TODO: handle exception
			products = null;
		} finally {
			session.close();
		}
		return products;
	}
	@Override
	public List<Product> queryAllByUserId(Integer user_id) {
		// TODO Auto-generated method stub
		String hql = "from Product product where product.user_id = ?";
		List<Product> products = new ArrayList<Product>();
		try {
			session = sessionFactory.openSession();
			Query query = session.createQuery(hql);
			query.setParameter(0, user_id); 
			products = query.list();
			System.out.println(products.size());
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
		}catch (IllegalArgumentException e) {//没有数据
			// TODO: handle exception
			products = null;
		} finally {
			session.close();
		}
		return products;
	}
	@Override
	public Product queryById(Integer id) {
		// TODO Auto-generated method stub
		Product product = new Product();
		try {
			session = sessionFactory.openSession();
			product = (Product) session.get(Product.class, id);
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			session.close();
		}
		return product;
	}
	@Override
	public Picture queryPictureById(Integer id) {
		// TODO Auto-generated method stub
		Picture picture = new Picture();
		String hql = "from Picture picture where picture.id = ?";
		try {
			session = sessionFactory.openSession();
			Query query = session.createQuery(hql);
			query.setParameter(0, id);
			picture =(Picture) query.list().get(0);
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			picture = null;
		}catch (IllegalArgumentException e) {//没有数据
			// TODO: handle exception
			picture = null;
			e.printStackTrace();
		} finally {
			session.close();
		}
		return picture;
	}
	@Override
	public List<Picture> queryPictureByProductId(Integer productId) {
		// TODO Auto-generated method stub
		List<Picture> pictures = new ArrayList<>();
		String hql = "from Picture picture where picture.product_id = ?";
		try {
			session = sessionFactory.openSession();
			Query query = session.createQuery(hql);
			query.setParameter(0, productId);
			pictures = query.list();
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			pictures = null;
		}catch (IllegalArgumentException e) {//没有数据
			// TODO: handle exception
			pictures = null;
			e.printStackTrace();
		} finally {
			session.close();
		}
		return pictures;
	}
	@Override
	public String delete(Integer id) {
		// TODO Auto-generated method stub
		String result = StringUtil.FAILURE;
		Product product = queryById(id);
		String dir = StringUtil.F_SAVE_DIRECTORY+"/"+ product.getUser_id() + "/" + product.getId() +"/";
		List<Picture> pic = queryPictureByProductId(id);
		if (product == null) {
			return StringUtil.FAILURE;
		}
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			session.delete(product);
			session.getTransaction().commit();
			for(int p=0; p< pic.size(); p++){
				Picture picture = pic.get(p) ; 
				deletePicture(picture);
			}
			Fileupload.delete(dir);
			return StringUtil.SUCCESS;
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			session.getTransaction().rollback();
			return StringUtil.FAILURE;
		} finally {
			session.close();
		}
	}
	@Override
	public String imageDelete(Integer picture_id) {
		// TODO Auto-generated method stub
		String result = StringUtil.FAILURE;
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			Picture picture = (Picture)session.get(Picture.class, picture_id);
			deletePicture(picture);
			session.delete(picture);
			session.getTransaction().commit();
			return StringUtil.SUCCESS;
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			session.getTransaction().rollback();
			return StringUtil.FAILURE;
		} finally {
			session.close();
		}
	}
	@Override
	public String update(Product product, Set pic) {
		// TODO Auto-generated method stub
		String result = StringUtil.FAILURE;
		try {
			session = sessionFactory.openSession();
			session.getTransaction().begin();
			session.update(product);
			Iterator<Picture> pIterator = pic.iterator();
			while (pIterator.hasNext()) {
				Picture pict = pIterator.next(); 
				session.save(pict);				
			}
			session.getTransaction().commit();
			result = StringUtil.SUCCESS;
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			session.getTransaction().rollback();
		} finally {
			session.close();
		}
		return result;
	}
	@Override
	public String update(Product product, List<File> pictures, List<String> picturesFileName) {
		// TODO Auto-generated method stub
		String result = StringUtil.FAILURE;
		try {
			session = sessionFactory.openSession();
			session.getTransaction().begin();
			session.update(product);
			Integer productId = product.getId(); 
			String dir = StringUtil.F_SAVE_DIRECTORY+"/"+ product.getUser_id() + "/" + product.getId() +"/";
			String loadRes = Fileupload.uploadFiles(dir, pictures, picturesFileName);
			if (!loadRes.equals(StringUtil.SUCCESS)) {
				return StringUtil.FAILURE;
			}
			String savePath = StringUtil.F_SAVE_PATH +"/"+ product.getUser_id() + "/" + product.getId() +"/";
			List<String> localPath = Fileupload.getLocalPaths(picturesFileName, savePath);
			//处理图片
			for (int i = 0; i < localPath.size(); i++) {
				Picture picture = new Picture();
				picture.setPath(localPath.get(i));
				picture.setProduct_id(productId);
				session.save(picture);	
			}
			session.getTransaction().commit();
			result = StringUtil.SUCCESS;
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			session.getTransaction().rollback();
		} finally {
			session.close();
		}
		return result;
	}
	private void deletePicture(Picture picture) {
		// TODO Auto-generated method stub
		String localPath = StringUtil.F_SAVE_DIRECTORY_D + picture.getPath();
		String featurePath = StringUtil.F_SAVE_DIRECTORY_D + picture.getFeature();
		String descriptorPath = StringUtil.F_SAVE_DIRECTORY_D + picture.getDescriptor();
		Fileupload.delete(localPath);
		Fileupload.delete(featurePath);
		Fileupload.delete(descriptorPath);
	}
	@Override
	public Integer getCountUserProduct(Integer userId) {
		// TODO Auto-generated method stub
		Integer result = 0;
		List count = new ArrayList<>();
		String sql = "select max(id) from product where user_id = ?";
		Query query;
		try {
			session = sessionFactory.openSession();
			query = session.createSQLQuery(sql);
			query.setParameter(0, userId);
			count = query.list();
			for(int i=0; i< count.size(); i++){
				System.out.println(count.get(i));
			}
			result = Integer.valueOf(count.get(0).toString());
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			session.close();
		}
		return result;
	}
	public Product getProduct() {
		return product;
	}
	public void setProduct(Product product) {
		this.product = product;
	}
	public Picture getPicture() {
		return picture;
	}
	public void setPicture(Picture picture) {
		this.picture = picture;
	}
	@Override
	public List<Product> queryAllProduct() {
		// TODO Auto-generated method stub
		String hql = "from Product product";
		List<Product> products = new ArrayList<Product>();
		try {
			session = sessionFactory.openSession();
			Query query = session.createQuery(hql);
			products = query.list();
			System.out.println(products.size());
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
		}catch (IllegalArgumentException e) {//没有数据
			// TODO: handle exception
			products = null;
		} finally {
			session.close();
		}
		return products;
	}
	@Override
	public List<Product> queryAllProduct(Integer pageNum, Integer pageSize) {
		// TODO Auto-generated method stub
		String hql = "from Product product";
		List<Product> products = new ArrayList<Product>();
		try {
			session = sessionFactory.openSession();
			Query query = session.createQuery(hql);
			query.setFirstResult((pageNum-1)*pageSize);
			query.setMaxResults(pageSize);
			products = query.list();
			System.out.println(products.size());
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
		}catch (IllegalArgumentException e) {//没有数据
			// TODO: handle exception
			products = null;
		} finally {
			session.close();
		}
		return products;
	}
}
